package tk.mybatis.springboot.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试限流请求接口
 * 平时使用场景 比如：
 * 1 、爬虫爬取一个网站，每秒请求有限制
 * 2、 你对接的第三方接口推送数据有数量限制，每秒钟只能请求200次等场景
 */
@Service
public class LimitHttpTest implements ApplicationContextAware {

    ApplicationContext applicationContext;
   static ConcurrentHashMap hashMap=new ConcurrentHashMap();

    @PostConstruct
    public void init() {
//        new Thread(() -> {
//            while (true){
//            }
//        }).start();
    }

    /**
     * 请求成功次数
     */
    public static int countSuccess = 1;

    public static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();


    public String test1() {
        String httpUrl = "test";
        LimitHttpTest bean = applicationContext.getBean(LimitHttpTest.class);
        bean.doTask(httpUrl);
        return httpUrl + " ok";
    }

    public String getCountAndQue() {
        int size = queue.size();
        return "queue size : " + size + " countSuccess:" + countSuccess;
    }

    @Async
    public void doTask(String httpUrl) {
        queue.add(httpUrl);

    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
